package com.server.net.session;

import com.msg.MsgMain;
import com.server.net.message.MsgNotWritableCacheManager;
import com.server.net.message.MsgPack;
import io.netty.channel.Channel;
import com.server.util.LogUtil;
import lombok.Data;

/**
 * 会话连接保持信息
 */
@Data
public class Session {

    private Channel channel;
    private String id;
    private String token;
    private long userId;
    private long roleId;

    public Session(Channel channel) {
        this.channel = channel;
        this.id = channel.id().asLongText();//asShortText不保证唯一性
        //初始化默认值
        this.token = "";
        this.userId = 0;
        this.roleId = 0;
    }

    /**
     * 发送信息
     */
    public boolean sendMsg(MsgMain.MainProtocl.Builder msg) {
        if (!channel.isActive()) {
            return false;
        }
        final int msgIndex = msg.getMessageType().getNumber();
        if (!channel.isWritable()) {
            //无法发送时，先暂时缓存
            MsgPack msgPack = new MsgPack(msgIndex, msg.build(), channel);
            MsgNotWritableCacheManager.getInstance().pushNotWritableMsg(msgPack);
            return false;
        }

        if (msgIndex % 2 == 1) {
            LogUtil.game.error("SC协议编号必须是偶数");
            return false;
        }
        channel.writeAndFlush(msg.build());
        LogUtil.game.info("【发出】" + msg.getMessageType().name() + ":" + msgIndex + "【channelId】" + id + "----" + msg.toString().replace("\n", ""));
        return true;
    }

}
